package com.will.willaicodemother.manage;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.will.willaicodemother.config.CosClientConfig;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @author will
 * @since 2025/8/20 17:36
 * 腾讯云对象存储管理类(通用的处理类)
 */
@Component
@Slf4j
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;


    /**
     * 上传对象
     * @param key 文件名
     * @param file 文件
     * @return PutObjectResult
     */
    private PutObjectResult putObject(String key, File file){
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 上传文件到对象存储并返回Url
     * @param key 文件名
     * @param file 文件
     * @return url
     */
    public String uploadFile(String key, File file){
        PutObjectResult putObjectResult = putObject(key, file);
        if (putObjectResult != null){
            String url = String.format("%s%s",cosClientConfig.getHost(), key);
            log.info("文件上传成功，本地路径：{},url: {}",file.getName(), url);
            return url;
        }else {
            log.error("文件上传失败，本地路径：{},返回结果为空",file.getName());
            return null;
        }
    }
}
